Skip to main content

Overview

The SigLipLoss class implements the sigmoid loss from the paper “Sigmoid Loss for Language Image Pre-Training” (SigLIP). Unlike standard CLIP’s softmax-based contrastive loss, SigLIP uses a sigmoid loss that:
  • Removes global normalization - No softmax across the batch
  • Per-pair loss computation - Each image-text pair is treated independently
  • Better scaling - More efficient for very large batch sizes
  • Improved performance - Often achieves better results than standard CLIP loss
The loss operates on pairwise similarities without requiring global batch statistics, making it particularly suitable for distributed training.

Reference

Class Definition

Initialization Parameters

bool
default:"False"
If True, caches ground truth labels to avoid recomputing them. Currently not actively used but reserved for future optimization.
int
default:"0"
Current process rank in distributed training.
int
default:"1"
Total number of processes in distributed training. Set to 1 for single-GPU training.
Optional[str]
default:"None"
Distributed implementation strategy. Options:
  • "bidir" (default) - Bidirectional exchange between neighboring ranks
  • "shift" - Sequential shift pattern through all ranks
  • "reduce" - All-reduce operations
  • "gather" - All-gather operations
The "bidir" strategy is generally most efficient.

Attributes

  • cache_labels: Whether label caching is enabled
  • rank: Current process rank
  • world_size: Total number of processes
  • dist_impl: Distribution strategy being used
  • prev_num_logits: Cached logits count (for potential future optimizations)
  • labels: Dictionary for cached labels (reserved for future use)

Key Methods

forward

Computes the sigmoid contrastive loss. Parameters:
  • image_features: Normalized image features of shape (batch_size, embed_dim)
  • text_features: Normalized text features of shape (batch_size, embed_dim)
  • logit_scale: Temperature parameter (typically model.logit_scale.exp())
  • logit_bias: Bias term added to logits (SigLIP typically uses a learned bias)
  • output_dict: If True, returns dict with key “contrastive_loss”, else returns scalar
Returns: Sigmoid contrastive loss value Note: Unlike ClipLoss, the logit_bias parameter is required (not optional) for SigLIP.

get_logits

Computes similarity logits between image and text features. Returns: Logits tensor of shape (batch_size, batch_size)

get_ground_truth

Generates ground truth labels for sigmoid loss. Parameters:
  • negative_only: If True, returns labels of all -1 (used for cross-GPU negative pairs)
Returns:
  • If negative_only=False: Matrix with +1 on diagonal, -1 elsewhere (matching pairs are positive)
  • If negative_only=True: Matrix of all -1 (all pairs are negative)

Usage Example

Distributed Training Example

Comparing Distribution Strategies

Dictionary Output

Mathematical Formulation

Given normalized image features IRN×DI \in \mathbb{R}^{N \times D} and text features TRN×DT \in \mathbb{R}^{N \times D}:
  1. Compute logits: zij=τ(iitj)+bz_{ij} = \tau \cdot (i_i^\top t_j) + b where τ\tau is logit_scale and bb is logit_bias
  2. Create targets: +1 & \text{if } i = j \text{ (matching pair)} \\ -1 & \text{otherwise (negative pair)} \end{cases}$$
  3. Compute loss: L=1Ni=1Nj=1Nlogσ(yijzij)\mathcal{L} = -\frac{1}{N} \sum_{i=1}^{N} \sum_{j=1}^{N} \log\sigma(y_{ij} \cdot z_{ij}) where σ(x)=11+ex\sigma(x) = \frac{1}{1 + e^{-x}} is the sigmoid function
  4. In distributed setting (with world_size > 1):
    • Compute local loss on diagonal pairs: (ii,ti)(i_i, t_i)
    • Exchange text features with other GPUs
    • Compute cross-GPU losses on off-diagonal pairs
    • Sum all losses

Key Differences from ClipLoss

Advantages of SigLIP

  1. Better scaling: Performance improves more consistently with larger batch sizes
  2. Memory efficient: No need to compute full batch softmax
  3. Simpler gradients: Each pair contributes independently
  4. Improved performance: Often achieves better zero-shot accuracy
  5. Distributed friendly: Natural decomposition for multi-GPU training

Distribution Strategy Guide

bidir (bidirectional exchange) - Default, recommended
  • Exchanges features with left and right neighbors simultaneously
  • Most efficient for typical multi-GPU setups
  • Requires world_size-1 exchanges in (world_size-1)/2 steps
shift - Sequential circular shift
  • Exchanges features in a ring pattern
  • Slightly slower than bidir but simpler
  • Requires world_size-1 sequential steps
reduce - All-reduce based
  • Uses all-reduce to broadcast one GPU’s features at a time
  • Less efficient but works on all hardware
  • Good fallback option
gather - All-gather based
  • Gathers all features to all GPUs
  • Most memory intensive
  • Simplest to understand

Best Practices

  1. Always use logit_bias with SigLIP:
  2. Use bidir strategy for distributed training:
  3. Normalize features before computing loss:
  4. Scale batch size larger than with ClipLoss:
    • SigLIP benefits more from large batches
    • Aim for 4096+ global batch size if possible
  5. Monitor logit_bias during training: